package vip.aster.websocket.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import vip.aster.websocket.config.WebSocketUsers;
import vip.aster.websocket.utils.WebSocketUtils;
import vip.aster.websocket.vo.WebSocketMessageVO;

import java.util.List;

/**
 * 订阅消息
 *
 * @author Aster
 * @since 2024/3/18 16:21
 */
@Slf4j
@Component
public class MessageReceiver implements MessageListener {

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 通道
        String channel = new String(message.getChannel());
        // 解析消息
        Object deserialize = WebSocketUtils.redisTemplate.getValueSerializer().deserialize(message.getBody());
        assert deserialize != null;
        WebSocketMessageVO broadcastMessage = new WebSocketMessageVO();
        if (deserialize instanceof WebSocketMessageVO) {
            broadcastMessage = (WebSocketMessageVO) deserialize;
        } else {
            broadcastMessage.setMessage(deserialize.toString());
        }

        // session key
        List<String> sessionKeys = broadcastMessage.getSessionKeys();
        // 消息内容
        String msg = broadcastMessage.getMessage();
        log.info("WebSocket主题订阅收到消息topic={} session={} message={}", channel, sessionKeys, msg);

        // 如果key不为空就按照key发消息 如果为空就群发
        if (CollUtil.isNotEmpty(sessionKeys)) {
            sessionKeys.forEach(key -> {
                if (WebSocketUsers.existSession(key)) {
                    WebSocketUtils.sendMessage(key, msg);
                }
            });
        } else {
            WebSocketUsers.getSessionsAll().forEach(key -> {
                WebSocketUtils.sendMessage(key, msg);
            });
        }
    }
}
